package org.jmsmith.utilities.io;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;


public class StreamCopier {

    private static final int BUF_ALLOC = 16 * 1024;
    private static final int EOF = -1;

    public void fastCopy(final InputStream src, final OutputStream dest) throws IOException {
        var inputChannel = Channels.newChannel(src);
        var outputChannel = Channels.newChannel(dest);
        var buffer = ByteBuffer.allocateDirect(BUF_ALLOC);

        while (inputChannel.read(buffer) != EOF) {
            buffer.flip();
            outputChannel.write(buffer);
            buffer.compact();
        }

        buffer.flip();

        while (buffer.hasRemaining()) {
            outputChannel.write(buffer);
        }
    }
}
